package logic

import (
	"context"
	"fmt"
	"product/model/mysql"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *productrpc.ListRequest) (*productrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var product []mysql.Good
	mysql.DB.Debug().Order("price desc").Offset(int(offset)).Limit(int(pageSize)).Where("user_id=?", in.UserId).Find(&product)
	fmt.Println(product)
	var products []*productrpc.List
	fmt.Println(products)
	for _, good := range product {
		list := productrpc.List{
			Image:  good.Image,
			Name:   good.Name,
			Price:  int64(good.Price),
			Num:    int64(good.Num),
			Intro:  good.Intro,
			UserId: int64(good.UserId),
			Id:     int64(good.ID),
		}
		products = append(products, &list)
	}
	fmt.Println(products)
	return &productrpc.ListResponse{List: products}, nil
}
